<?php


class WSB_Db_Row extends Zend_Db_Table_Row_Abstract
{

	/**
	 * @var string
	 */
	protected $_formConfigPath;

	/**
	 * @param string $key
	 * @return string
	 */
	public function translate($key)
	{
		return $this->_table->translate($key);
	}

	/**
	 * @return string|array
	 */
	public function getPrimary()
	{
		return $this->_table->getPrimary();
	}

	/**
	 * @return string
	 */
	public function getPrimaryValue()
	{
		$primary = $this->_table->getPrimary();
		return $this->_data[$primary];
	}

	/**
	 * @return array
	 */
	public function info()
	{
		return $this->_table->info();
	}

	/**
	 * @return string
	 */
	public function getTableName()
	{
		return $this->_table->getName();
	}

	/**
	 * @param string|array $columns
	 * @return boolean
	 */
	public function hasParentTable($columns)
	{
		$parentTable = $this->_findParentTableByColumns($columns);
		return empty($parentTable) ? false : true;
	}

	/**
	 * @param string|array $columns
	 * @return string
	 */
	private function _findParentTableByColumns($columns)
	{
		if(!is_string($columns) && !is_array($columns)) {
			throw new Exception('Columns has to be an array or a string.');
		}
		$parentTable = null;
		foreach($this->_table->getReferences() AS $key=>$reference) {
			if(is_array($reference['columns'])) {
				if(is_array($columns)) {
					if($reference['columns'] == $columns) {
						die('NOT YET IMPLEMENTED');
						break;
					}
				} elseif(is_string($columns)) {
					if(reset($reference['columns']) == $columns) {
						$parentTable = $reference['refTableClass'];
						break;
					}
				}
			}
		}
		return $parentTable;
	}

	/**
	 * @param string|array $columns
	 * @return Zend_Db_Table_Abstract
	 */
	public function getParentTableByColumns($columns)
	{
		$parentTable = $this->_findParentTableByColumns($columns);
		if(!empty($parentTable)) {
	        try {
	            Zend_Loader::loadClass($parentTable);
	        } catch (Zend_Exception $e) {
	            throw new Exception($e->getMessage());
	        }
	        return new $parentTable();
		}
		return null;
	}

	/**
	 * @return string
	 */
	public function getTitle()
	{
		return sprintf('Overwrite %s::getTitle()', get_class($this));
	}

	/**
	 * Uebersteuert Zend_Db_Table_Row_Abstract::delete()
	 *
	 * @return int The number of rows deleted.
	 */
    public function delete()
    {
    	// Falls es eine Spalte "deleted" gibt, wird der Datensatz nur
    	// als gelöscht markiert. Andernfalls wird der Eintrag wirklich aus
    	// der Tabelle gelöscht.
		if(isset($this->deleted)) {
			$where = $this->_getWhereQuery();
			$data = array('deleted' => 1);
			return $this->_getTable()->update($data, $where);
		} else {
			$where = $this->_getWhereQuery();
			return $this->_getTable()->delete($where);
		}
    }

    /**
     * Die preSave-Mehtode wird innerhalb der save-Methode als erstes
     * aufgerufen und kann genutzt werden, um Werte zu manipulieren.
     *
     */
    public function preSave()
    {}

    /**
     * Uebersteuert Zend_Db_Table_Row_Abstract::save()
     * If the _cleanData array is empty,
     * this is an INSERT of a new row.
     * Otherwise it is an UPDATE.
     *
     * @return mixed The primary key value(s), as an associative array if the
     *     key is compound, or a scalar if the key is single-column.
     */
    public function save()
    {
    	$this->preSave();

    	// Info
        $info = $this->info();

    	// hidden
    	if(isset($this->hidden) && !is_numeric($this->hidden)) {
   			$this->hidden = 0;
    	}
    	// deleted
    	if(isset($this->deleted) && !is_numeric($this->deleted)) {
   			$this->deleted = 0;
    	}
        if(empty($this->_cleanData)) {
        	// created
        	if(isset($this->created)) {
        		if($info['metadata']['created']['DATA_TYPE'] == 'timestamp') {
        			$this->created = date('Y-m-d H:i:s'); // 2009-03-23 11:11:07
        		} else {
        			$this->created = time();
        		}
        	}
            //return $this->_doInsert();
        } else {
        	// modified
        	if(isset($this->modified)) {
        		if($info['metadata']['modified']['DATA_TYPE'] == 'timestamp') {
        			$this->modified = date('Y-m-d H:i:s'); // 2009-03-23 11:11:07
        		} else {
	        		$this->modified = time();
        		}
        	}
            //return $this->_doUpdate();
        }

        $cols = array_diff($info['cols'], array('hidden', 'deleted', 'created', 'modified'));
        foreach($cols AS $col) {
        	if($info['metadata'][$col]['NULLABLE']) {
				if($this->$col === '') {
					$this->$col = NULL;
				} elseif($this->$col === 0) {
					$this->$col = NULL;
				}
        	}
        }
        return parent::save();
    }

	/**
	 * Get the form for this table row and overwrite with config settings if INI-file exists.
	 *
	 * @return Zend_Form
	 */
    public function getForm()
	{
		$editor = $this->getFormEditor();
    	return $editor->getForm();
    }

    /**
     * Get the form editor for this table row, overwritten with config settings if INI-file exists.
     *
     * @return WSB_Form_Editor
     */
    public function getFormEditor()
	{
    	$editor = new WSB_Form_Editor($this);
		if(!empty($this->_formConfigPath) && is_file($this->_formConfigPath)) {
			$config = new Zend_Config_Ini($this->_formConfigPath);
			$editor->overwriteWithConfig($config);
		}
		return $editor;
    }

}